package com.iflytek.jcy.supervise.clue.component.config;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

import com.iflytek.jcy.supervise.clue.common.util.ThreadPoolUtils;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * @author <a href=mailto:ktyi@iflytek.com>伊开堂</a>
 * @date 2022/9/19
 */
@Data
@ConfigurationProperties(prefix = "thread-pool")
public class ThreadPoolProperties {

    private PoolConfigInfo common = new PoolConfigInfo();

    @Data
    public static class PoolConfigInfo {
        private int threadSize = ThreadPoolUtils.CPU_SIZE;
        private String threadNamePrefix = "Custom-Thread";
        private int queueCapacity = Integer.MAX_VALUE;
        private RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy();

        public void setRejectedExecutionHandler(String rejectedExecutionHandler) {
            if (StringUtils.isBlank(rejectedExecutionHandler)) {
                return;
            }

            RejectedExecutionHandler handler = null;
            switch (rejectedExecutionHandler) {
                case "CallerRunsPolicy":
                    handler = new ThreadPoolExecutor.CallerRunsPolicy();
                    break;
                case "AbortPolicy":
                    handler = new ThreadPoolExecutor.AbortPolicy();
                    break;
                case "DiscardOldestPolicy":
                    handler = new ThreadPoolExecutor.DiscardOldestPolicy();
                    break;
                case "DiscardPolicy":
                    handler = new ThreadPoolExecutor.DiscardPolicy();
                    break;
                default:
                    return;
            }
            this.rejectedExecutionHandler = handler;
        }
    }

}
